const express = require('express');
const bcrypt = require('bcryptjs')

const Task = require('../../models/task')
const Taskaudit = require('../../models/taskaudit')

const response = require('../../utils/response')
const {
    hanleTask,
    handleCate,
    deletaTask,
    huanTime
} = require('../../utils/tool');

const router = express.Router(); +

// 添加
router.post('/', async (req, res) => {

    //用户添加
    if (req.Model.modelName === 'User') {
        const {
            password
        } = req.body
        req.body.password = bcrypt.hashSync(password, 10)
    }

    //分类添加
    if (req.Model.modelName === 'Category') {
        let {
            name,
            parentId
        } = req.body
        let grade = 0 //初始任务等级
        if (parentId.length > 0) {
            parentId = parentId[parentId.length - 1]
            let cate = await req.Model.findById(parentId)
            grade = cate.grade + 1
        }
        let data = {
            name,
            parentId,
            grade
        }

        const cate = req.Model.create(data)
        res.send(cate)
        return
    }

    //提交审核
    if (req.Model.modelName === 'TaskAudit') {

        let {
            taskId
        } = req.body

        let task = await Task.findById(taskId).lean()
        //校验任务状态和进度
        if (task.status === 0 || task.status === 1 || task.process < 100) return res.status(402).send({
            message: '任务状态或进度未完成~~'
        })

        let data = await req.Model.find({
            taskId,
            void: 0
        })
        // 校验重复
        if (data.length > 0) return res.status(422).send({
            message: '请勿重复提交审核~~'
        })

        //改变任务提交状态
        // let task = await Task.findById(taskId).lean()
        task.status = 3
        let upTask = await Task.findByIdAndUpdate(taskId, task)

        req.body.taskname = task.taskname
    }

    //任务添加
    if (req.Model.modelName === 'Task') {
        let data = req.body
        if (data.parentId) {
            let parent = await req.Model.findById(data.parentId)
            data.grade = parent.grade + 1
        }
        //转化时间
        if (!data.endtime) return response(res, 401, "结束时间不能为空~~")

        data.endtime = huanTime(data.endtime)
        // const model = await req.Model.create(data)
        let task = new req.Model(data)
        task.fileAddress = []
        task.createdAt = huanTime(Date.now())
        task.updatedAt = huanTime(Date.now())
        await task.save()
        res.send(task)
        return
    }
    const model = await req.Model.create(req.body)
    res.send(model)
})

// 获取列表
router.get('/', async (req, res) => {

    //查询成员列表
    if (req.Model.modelName === 'User') {
        let {
            pagenum,
            pagesize,
            query
        } = req.query
        pagenum = parseInt(pagenum)
        pagesize = parseInt(pagesize)
        let model = await req.Model.find({
            name: {
                $regex: query
            }
        }).populate('position rofessional').sort({
            _id: -1
        }).skip((pagenum - 1) * pagesize).limit(pagesize).lean()

        //总数
        let total = await req.Model.find({
            name: {
                $regex: query
            }
        }).count()

        response(res, 200, '获取用户列表成功', {
            pagenum,
            total,
            model
        })
        return
    }

    //查询任务列表
    if (req.Model.modelName === 'Task') {
        let {
            pagenum,
            pagesize,
            query
        } = req.query
        pagenum = parseInt(pagenum)
        pagesize = parseInt(pagesize)

        if (query == '') {
            let model = await req.Model.find({
                grade: 0,
            }).populate('worker', ['name']).populate('creator', ['name']).sort({
                _id: -1
            }).skip((pagenum - 1) * pagesize).limit(pagesize).lean()
            let arr = []
            await hanleTask(model, arr)
            model = arr[arr.length - 1]
            //总数
            let total = await Task.find({
                grade: 0,
            }).count()
            response(res, 200, '获取任务列表成功', {
                pagenum,
                total,
                model
            })
        } else {
            let model = await req.Model.find({
                taskname: {
                    $regex: query
                }
            }).populate('worker', ['name']).populate('creator', ['name']).sort({
                _id: -1
            }).skip((pagenum - 1) * pagesize).limit(pagesize).lean()
            let arr = []
            await hanleTask(model, arr)
            model = arr[arr.length - 1]
            //总数
            let total = await Task.find({
                taskname: {
                    $regex: query
                }
            }).count()
            response(res, 200, '获取任务列表成功', {
                pagenum,
                total,
                model
            })
        }



        return
    }

    //获取分类列表
    if (req.Model.modelName === 'Category') {
        let {
            pagenum,
            pagesize,
            query
        } = req.query
        pagenum = parseInt(pagenum)
        pagesize = parseInt(pagesize)
        let model = await req.Model.find({
            grade: 0,
            name: {
                $regex: query
            }
        }).populate('parentId').sort({
            _id: -1
        }).skip((pagenum - 1) * pagesize).limit(pagesize).lean()

        let arr = []
        await handleCate(model, arr)
        model = arr[arr.length - 1]

        //总数
        let total = await req.Model.find({
            grade: 0,
            name: {
                $regex: query
            }
        }).count()

        response(res, 200, '获取分类列表成功', {
            pagenum,
            total,
            model
        })

        return
    }

    //查询审核表
    if (req.Model.modelName === 'TaskAudit') {
        let {
            pagenum,
            pagesize,
            query
        } = req.query
        pagenum = parseInt(pagenum)
        pagesize = parseInt(pagesize)
        const model = await req.Model.find({
            taskname: {
                $regex: query
            }
        }).populate('reviewer taskId').sort({
            _id: -1
        }).skip((pagenum - 1) * pagesize).limit(pagesize).lean()

        //总数
        let total = await req.Model.find({
            taskname: {
                $regex: query
            }
        }).count()

        response(res, 200, '获取审核列表成功', {
            pagenum,
            total,
            model
        })

        return
    }

    const model = await req.Model.find().sort({
        _id: -1
    })
    res.send(model)
})

// 根据ID获取单个数据
router.get('/:id', async (req, res) => {

    //查询审核信息
    if (req.Model.modelName === 'TaskAudit') {
        const model = await req.Model.findById(req.params.id).populate('reviewer taskId').lean()
        res.send(model)
        return
    }
    // //查询任务信息
    // if (req.Model.modelName === 'Task') {
    //     const model = await req.Model.findById(req.params.id).populate('worker').lean()
    //     res.send(model)
    //     return
    // }

    const model = await req.Model.findById(req.params.id)
    res.send(model)
})

// 根据ID编辑
router.put('/:id', async (req, res) => {

    // 任务修改
    // if (req.Model.modelName === 'Task'){
    //     let id = req.params.id
    //     console.log(req.body);
    //     return
    //     const model = await req.Model.findByIdAndUpdate(id, req.body)
    //     res.send(model)

    //     return
    // }

    let id = req.params.id
    const model = await req.Model.findByIdAndUpdate(id, req.body)
    res.send(model)
})

// 删除
router.delete('/:id', async (req, res) => {


    //删除顶级任务
    if (req.Model.modelName === 'Task') {
        let id = req.params.id
        const model = await req.Model.findByIdAndDelete(id)
        //删除审核表里所属的顶级任务
        await Taskaudit.deleteMany({
            taskId: id
        })

        await deletaTask(id)

        res.send()
        return
    }

    let id = req.params.id
    const model = await req.Model.findByIdAndDelete(id)

    res.send({
        success: true
    })
})

module.exports = router;